package com.rfy.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author zhang
 *
 */
@Component("springUtil")
public class SpringUtil {

    private static ApplicationContext applicationContext = null;

    /**
     * 非@import显式注入，@Component是必须的，且该类必须与main同包或子包
     * 若非同包或子包，则需手动import 注入，有没有@Component都一样
     * 可复制到Test同包测试
     *
     * @param applicationContext
     * @throws BeansException
     */

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    /**
     * 获取上下文对象
     *
     * @return context
     */
    public static ApplicationContext getContext() {
        return applicationContext;
    }

    /**
     * 判断上下文对象是否为空
     *
     * @return
     */
    public static boolean checkapplicationContext() {
        return getContext() != null;
    }

    /**
     * 根据name获取bean
     *
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (checkapplicationContext()) {
            return (T) getContext().getBean(name);
        } else {
            return null;
        }
    }

    /**
     * 根据class 获取bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (checkapplicationContext()) {
            return getContext().getBean(clazz);
        } else {
            return null;
        }
    }

    /**
     * 根据name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        if (checkapplicationContext()) {
            return getContext().getBean(name, clazz);
        } else {
            return null;
        }
    }
}
